<?php

/**
 * Created by PhpStorm.
 * User: yf
 * Date: 2018/3/3
 * Time: 下午6:18
 */
namespace App\HttpController\Api;

use EasySwoole\Core\Http\AbstractInterface\Controller;
use EasySwoole\Core\Http\Message\Status;
use App\Msg\MsgInfo;
use App\Utility\BaseException;
use App\Msg\MsgCode;
use App\Utility\Validator;
use App\Model\User\UserModel;
use App\Model\User\UserBean;

abstract class AbstractBase extends Controller {
	public $token = "";
	public $userInfo = null;
	function index() {
		// TODO: Implement index() method.
		$this->actionNotFound ( 'index ' );
	}
	
	// onRequest返回false的时候，为拦截请求，不再往下执行方法
	protected function onRequest($action): ?bool {
		if ($action != "login" && $action != "register") {
			$token = $this->request ()->getQueryParam ( "token" );
			$this->token = $token;
			$this->checkViewForm ( Validator::isEmpty ( $token ), MsgCode::TOKEN_IS_NULL );
			$userinfo = (new UserModel ())->getUserByToken ( $token );
			if (empty ( $userinfo->getUid () )) {
				$this->jsonReturn ( MsgCode::USER_NOT_LOGIN, [ ] );
				return false;
			} else {
				$this->userInfo = $userinfo;
				return true;
			}
		} else {
			return true;
		}
	}
	function getUserInfo(): UserBean {
		return $this->userInfo;
	}
	protected function actionNotFound($action): void {
		$this->writeJson ( Status::CODE_NOT_FOUND );
	}
	protected function onException(\Throwable $throwable, $actionName): void {
		// 若重载实现了onException 方法，那么控制器内发生任何的异常，都会被该方法拦截，该方法决定了如何向客户端响应
		$this->writeJson ( $throwable->getCode (), [ 
				'info' => "error action is " . $actionName 
		], $throwable->getMessage () );
	}
	function checkViewForm(Bool $logicStatic, int $code, string $msg = "", $action = "User") {
		if (empty ( $msg )) {
			$msg = MsgInfo::$action ( $code );
		}
		if (! $logicStatic) {
			throw new BaseException ( [ 
					'msg' => $msg,
					'code' => $code 
			] );
		}
		return $this;
	}
	function jsonReturn($code, $data, $action = "User") {
		if ($code == Status::CODE_OK) {
			$this->writeJson ( $code, $data, "" );
		} else {
			$this->writeJson ( $code, $data, MsgInfo::$action ( $code ) );
		}
	}
}